package com.ruoyi.orm.ds;

import java.util.HashMap;
import java.util.Map;

import com.zaxxer.hikari.HikariDataSource;


/**
 * 数据源缓存池
 */
public class DataSourceCachePool {
    /** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */
    private static Map<String, HikariDataSource> dbSources = new HashMap<>();

    /**
     * 获取多数据源缓存
     *
     * @param dbKey
     * @return
     */
    public static DynamicDataSourceModel getCacheDynamicDataSourceModel(String dbKey) {
        DynamicDataSourceModel dbSource = null;//commonApi.getDynamicDbSourceByCode(dbKey);
        return dbSource;
    }

    public static HikariDataSource getCacheBasicDataSource(String dbKey) {
        return dbSources.get(dbKey);
    }

    /**
     * put 数据源缓存
     *
     * @param dbKey
     * @param db
     */
    public static void putCacheBasicDataSource(String dbKey, HikariDataSource db) {
        dbSources.put(dbKey, db);
    }

    /**
     * 清空数据源缓存
     */
    public static void cleanAllCache() {
        //关闭数据源连接
        for(Map.Entry<String, HikariDataSource> entry : dbSources.entrySet()){
            String dbkey = entry.getKey();
            HikariDataSource druidDataSource = entry.getValue();
            if(druidDataSource!=null && druidDataSource.isRunning()){
                druidDataSource.close();
            }
        }
        //清空缓存
        dbSources.clear();
    }

    public static void removeCache(String dbKey) {
        //关闭数据源连接
    	HikariDataSource druidDataSource = dbSources.get(dbKey);
        if(druidDataSource!=null && druidDataSource.isRunning()){
            druidDataSource.close();
        }
        //清空缓存
        dbSources.remove(dbKey);
    }

}
